package entityAdapter

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisTag"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeTSQL"
	"time"
)

type deviceSequenceRecordAdapter struct {
	lastTime int64
}

func (e *deviceSequenceRecordAdapter) SaveDeviceSequenceRecord(deviceName string, record map[string]interface{}) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if record == nil || deviceName == "" {
		return
	}

	// 检查：是否需要记录
	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}
	deviceSequenceRecord := Map.GetMap(configs, "deviceSequenceRecord", make(map[string]interface{}))
	if !Map.GetBool(deviceSequenceRecord, "enable", false) {
		return
	}

	deviceValue := record["deviceValue"]
	metricName := record["metricName"]
	timestamp := record["timestamp"]
	if Method.HasEmpty(deviceValue) || Method.HasEmpty(metricName) || timestamp == nil {
		return
	}

	recordEntity := edgeEntity.Type.DeviceSequenceEntity.Instance()
	recordEntity.DeviceName = deviceName
	recordEntity.MetricName = metricName.(string)
	recordEntity.Timestamp = Number.MakeInt64(timestamp)
	recordEntity.DeviceValue = deviceValue.(map[string]interface{})

	// 保存到数据库
	err = edgeTSQL.InsertRecord(recordEntity)
	if err != nil {
		return
	}

	// 更新标记
	commRedisTag.Service.SetValue(recordEntity.Type(), recordEntity)
}

func (e *deviceSequenceRecordAdapter) ClearDeviceSequenceRecord() {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if !commEntityManager.EntityManager.Initialized {
		return
	}

	// 检查：是否需要记录
	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}

	value := Map.GetOrDefault(configs, "deviceSequenceRecord", make(map[string]interface{}))
	params := value.(map[string]interface{})

	maxHour := Number.MakeInt(Map.GetOrDefault(params, "maxHour", 72))
	period := Number.MakeInt64(Map.GetOrDefault(params, "period", 3600))

	// 检查：执行周期是否到达
	currentTime := time.Now().UnixMilli()
	if (currentTime - e.lastTime) < period*1000 {
		return
	}
	e.lastTime = currentTime

	// 除了最近的maxCount条数据，旧数据全部删除
	e.deleteDeviceRecord(maxHour)
}

func (e *deviceSequenceRecordAdapter) deleteDeviceRecord(maxHour int) {
	edgeTSQL.DeleteRecords(maxHour)
}
